package index;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String inputCaptcha = request.getParameter("captcha");
        String sessionCaptcha = (String) request.getSession().getAttribute("CAPTCHA");

        // 验证码校验
        if (!inputCaptcha.equalsIgnoreCase(sessionCaptcha)) {
            request.setAttribute("registerError", "验证码错误");
            request.getRequestDispatcher("loginRegister.jsp").forward(request, response);
            return;
        }

        // 用户名校验
        if (JdbcUtils.isUserExists(username)) {
            request.setAttribute("registerError", "用户名已存在");
            request.getRequestDispatcher("loginRegister.jsp").forward(request, response);
            return;
        }
        if ("admin".equalsIgnoreCase(username)) {
            request.setAttribute("registerError", "该用户名不可用");
            request.getRequestDispatcher("loginRegister.jsp").forward(request, response);
            return;
        }

        // MD5加密
        String hashedPwd = md5(password);

        // 注册用户
        if (JdbcUtils.registerUser(username, hashedPwd)) {
            response.sendRedirect("index.jsp?register=success");
        } else {
            request.setAttribute("registerError", "注册失败，请重试");
            request.getRequestDispatcher("loginRegister.jsp").forward(request, response);
        }
    }

    private String md5(String input) {
        // 与登录相同的加密逻辑
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            return input;
        }
    }
}
